package com.innovation.ic.b1b.framework.manager;


import org.springframework.data.mongodb.core.BulkOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

public class MongodbManager {

    private MongoTemplate mongoTemplate;

    public MongodbManager(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }

    /**
     * 查找数据
     *
     * @param query
     * @param clazz
     * @param <T>
     * @return
     */
    public <T> List<T> find(Query query, Class<T> clazz) {
        return this.mongoTemplate.find(query, clazz);
    }

    /**
     * 查询所有
     *
     * @param clazz
     * @param <T>
     * @return
     */
    public <T> List<T> findAll(Class<T> clazz) {
        return this.mongoTemplate.findAll(clazz);
    }

    /**
     * 更新数据
     *
     * @param query
     * @param update
     * @param clazz
     * @param <T>
     */
    public <T> void updateFirst(Query query, Update update, Class<T> clazz) {
        this.mongoTemplate.updateFirst(query, update, clazz);
    }

    /**
     * 插入数据
     *
     * @param t
     * @param <T>
     * @return
     */
    public <T> T insert(T t) {
        return (T) this.mongoTemplate.insert(t);
    }

    /**
     * 查找单条数据
     *
     * @param query
     * @param entityClass
     * @param <T>
     * @return
     */

    public <T> T findOne(Query query, Class<T> entityClass) {
        return this.mongoTemplate.findOne(query, entityClass);
    }

    /**
     * 条件删除数据
     *
     * @param query
     * @param clazz
     * @param <T>
     */
    public <T> void remove(Query query, Class<T> clazz) {
        this.mongoTemplate.remove(query, clazz);
    }

    /**
     * 条件统计
     *
     * @param query
     * @param clazz
     * @param <T>
     * @return
     */
    public <T> long count(Query query, Class<T> clazz) {
        return this.mongoTemplate.count(query, clazz);
    }

    /**
     * 批量插入
     *
     * @param clazz
     * @param classList
     * @param <T>
     */
    public <T> void bulkOpsInsert(Class<T> clazz, List<T> classList) {
        this.mongoTemplate.bulkOps(BulkOperations.BulkMode.UNORDERED, clazz).insert(classList).execute();
    }
}
